package cn.brilliantfuture.commentry.store.impl;

import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jboss.wsf.spi.annotation.WebContext;

import cn.brilliantfuture.commentry.entity.ReservePlan;
import cn.brilliantfuture.commentry.store.StoreInfoMessageRemote;
import cn.brilliantfuture.commentry.store.StoreInfoMessageWebService;
import cn.brilliantfuture.commentry.util.RESTUtil;

/**
 * 
 * Title: Communication Entry
 * 
 * Author:  LiTian  
 *
 * Date: 2013-9-16
 * 
 * Description:
 * 
 */
@Stateless
@WebService(endpointInterface = "cn.brilliantfuture.commentry.store.StoreInfoMessageWebService")
@WebContext(contextRoot = "/commentry", urlPattern = "/StoreInfoMessageWebService")
public class StoreInfoMessageImpl implements StoreInfoMessageWebService, StoreInfoMessageRemote {

	private static Logger logger = Logger.getLogger(StoreKeysMessageImpl.class);
	
	@PersistenceContext
	EntityManager entityManager;
	
	public void getStoreReserveDone(Integer[] reservePlanIds, Integer[] serviceTypes, Integer[] reserveTypes) {
		logger.info("reservePlanIds -> " + reservePlanIds + " serviceTypes -> " + serviceTypes + " reserveTypes -> " + reserveTypes);
		
		JSONArray sources = new JSONArray();
		JSONArray services = new JSONArray();
		JSONArray reserves = new JSONArray();
		
		for (int i = 0; i < reservePlanIds.length; i++) {
			int id = reservePlanIds[i];
			int serviceType = serviceTypes[i];
			int reserveType = reserveTypes[i];
			
			ReservePlan reservePlan = entityManager.find(ReservePlan.class, id);
			
			if (null != reservePlan){
				if (reservePlan.getServiceType().intValue() == serviceType && reservePlan.getReserveType().intValue() == reserveType) {
					if (reservePlan.getReserveType().intValue() == 1) {
						reservePlan.setPublish(true);
						reservePlan.setUsed(true);
					} else if (reservePlan.getReserveType().intValue() == 2) {
						reservePlan.setPublish(true);
						reservePlan.setUsed(false);
					}
					
					entityManager.merge(reservePlan);
				}
				
				sources.add(id);
				services.add(serviceType);
				reserves.add(reserveType);
			}
		}
		
		JSONObject field = new JSONObject();
		field.accumulate("source_plan_ids", sources);
		field.accumulate("service_types", services);
		field.accumulate("reserve_types", reserves);
		
		entityManager.flush();
		
		String result = RESTUtil.getRESTInvoke(RESTUtil.STORE_RESERVE_CALLBACK_METHOD, field.toString());
		
		logger.info("result -> " + result);
	}
}
